﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Api.Application.Command.DeviceManage.Project;
using ProduceBasicData.Domain.DeviceManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.DeviceManage.Project
{
    /// <summary>
    /// 项目维护创建处理器
    /// </summary>
    public class CreateProjectMaintenanceHandler : IRequestHandler<CreateProjectMaintenanceCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProjectMaintenance> _projectMaintenanceRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="projectMaintenanceRepository"></param>
        /// <param name="mapper"></param>
        public CreateProjectMaintenanceHandler(IBaseRespository<ProjectMaintenance> projectMaintenanceRepository, IMapper mapper)
        {
            _projectMaintenanceRepository = projectMaintenanceRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理项目维护录入请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(CreateProjectMaintenanceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //将命令转换为领域模型
                var ProjectMaintenance = _mapper.Map<ProjectMaintenance>(request);
                //判断项目维护是否存在
                var ProjectMaintenanceExist = await _projectMaintenanceRepository.GetAll().AnyAsync(x => x.ProjectName == ProjectMaintenance.ProjectName);
                if (ProjectMaintenanceExist != false)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "项目维护已存在"
                    };
                }
                //保存项目维护
                var result = await _projectMaintenanceRepository.AddAsync(ProjectMaintenance);
                if (result > 0)
                {
                    return new ApiResult<int>
                    {
                        Data = result,
                        Code = ApiEnum.Success,
                        Msg = "项目维护录入成功"
                    };
                }
                else
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "项目维护录入失败"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = ex.Message
                };
            }
        }
    }
}
